#include "task_rs485_comm.h"
#include "FSMC_SRAM.h"

#include "FreeRTOS.h"
#include "task.h"

#include "module_rs485_driver.h"
#include "print_rtt.h"
#include "rs485_comm_analyse.h"
#include "rs485_port_init.h"
#include "string.h"

#include "device_resource.h"
#include "private_mqtt_publish_msg.h"
#include "unit_status_common.h"
static StackType_t xRs485CommStack[256]; // 静态栈
static StaticTask_t xRs485CommTCB;       // 静态 TCB（可选，省堆）
uint16_t receive_bytes_lenth;
uint16_t send_bytes_lenth;
/**
 * @brief RS485通信任务入口函数
 * @param pvParameters 任务参数（本函数中未使用）
 * @note 这是一个无限循环的任务，用于处理RS485通信
 */
static void vRs485CommTaskEntry(void *pvParameters)
{
  (void)pvParameters; // 避免未使用参数的警告
  int ret;
  for (;;) // 无限循环，持续运行通信任务
  {
    if (0 == get_need_send_to_relay_order(&r485_cs.com_status, SEND_BYTES, &send_bytes_lenth))
    {

#ifdef DEBUG_RS485
      //   LOG_INFO("SEND :%d\r\n", send_bytes_lenth);
      //   LOG_BYTE(SEND_BYTES, send_bytes_lenth);
#endif
      receive_bytes_lenth = 0;
      memset(RECEIVE_BYTES, 0, RECEIVE_BUFFER_LENTH);
      ret = rs485_private_send_out_order_and_fetch_response(&moudule_rs485,
                                                            0,
                                                            SEND_BYTES,
                                                            send_bytes_lenth,
                                                            RECEIVE_BYTES,
                                                            &receive_bytes_lenth,
                                                            100);
#ifdef DEBUG_RS485
      if (ret == -1)
      {
        uint8_t channel = r485_cs.com_status.cro_st.ctrl_unit_index;
        // LOG_INFO("ret:%d,RECEIVE NONE!\r\n", ret);
        //不在线，发送不在线
        if (send_message[channel].message2.online != 0)
        {
          send_message[channel].message2.online = 0;
          send_message[channel].message2.need_updata_flag = 1;
        }
        else
        {
          if (((device_time_ms_tickets / 1000) - send_message[channel].message2.last_send_time) >= 300)
          {
            send_message[channel].message2.need_updata_flag = 1;
          }
        }
        if (send_message[channel].message2.need_updata_flag == 1)
        {
          send_message[channel].message2.last_send_time = (device_time_ms_tickets / 1000);
          uint8_t box = get_box_from_bound_index(channel);
          if (box == 0xFF)
          {
            return;
          }
          publish_message2_status(publish_id++, box, &send_message[channel].message2);
          send_message[channel].message2.need_updata_flag = 0;
        }
      }
      else
      {
        if (show_rs485 == 1)
        {

          LOG_INFO("ret:%d,RECEIVE :%d\r\n", ret, receive_bytes_lenth);
          LOG_BYTE(RECEIVE_BYTES, receive_bytes_lenth);
        }
      }

#endif

      analyse_receive_response(&r485_cs.com_status, ret, RECEIVE_BYTES, receive_bytes_lenth);
    }
    vTaskDelay(pdMS_TO_TICKS(100));
  }
}

void vRs485CommTaskCreate(void)
{
  TaskHandle_t xHandle = NULL;
  taskENTER_CRITICAL(); // 进入临界区
  rs485_com_comm_and_relay_unit_status_init(&r485_cs.com_status);
  module_rs485_driver_init();

  /* 创建system_led任务 - 静态方法 */
  xHandle = xTaskCreateStatic(
      (TaskFunction_t)vRs485CommTaskEntry,                     /* 任务入口函数 */
      (const char *)"rs485_comm",                              /* 任务名字 */
      (uint16_t)sizeof(xRs485CommStack) / sizeof(StackType_t), /* 任务栈大小 */
      (void *)NULL,                                            /* 任务入口函数参数 */
      (UBaseType_t)5,                                          /* 任务的优先级 */
      (StackType_t *)xRs485CommStack,                          /* 静态栈数组 */
      (StaticTask_t *)&xRs485CommTCB);                         /* 静态TCB的地址 */

  if (xHandle != NULL)
  {
    LOG_INFO("Create rs485 comm Task success!\r\n");
  }
  taskEXIT_CRITICAL(); // 退出临界区，无论成功失败都要退出
}
